package com.spdg.ring;

import java.util.List;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.text.Html;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.widget.TextView;
import cn.wolf.http.HttpCallBack;
import cn.wolf.notify.NotificationConstants;
import cn.wolf.notify.NotificationEntity.Message;
import cn.wolf.tools.AlertHelper;
import cn.wolf.tools.AppHelper;
import cn.wolf.tools.CommonUtils;
import cn.wolf.tools.SharedPreferencesUtil;
import cn.wolf.tools.StringUtil;

import com.spdg.ring.bo.ArticleBo;
import com.spdg.ring.bo.MenuBo;
import com.spdg.ring.common.Config;
import com.spdg.ring.common.Key;
import com.spdg.ring.datamgr.ArticleDataMgr;
import com.spdg.ring.datamgr.MenuDataMgr;
import com.spdg.ring.resp.ArticleResp;
import com.spdg.ring.resp.MenuResp;
import com.spdg.ring.sqlite.model.Article;
import com.spdg.ring.sqlite.model.Menu;

/**
 * <p>Title:  文章详细界面</p>
 * <p>Description:  </p>
 * <p>@author: caijj , Eric.wsd    </p>
 * <p>Copyright: Copyright (c) 2012    </p>
 * <p>Company: HX Co., Ltd.          </p>
 * <p>Create Time: 2012-10-22             </p>
 * <p>Update Time:                     </p>
 * <p>Updater:                         </p>
 * <p>Update Comments:                 </p>
 */
public class PushArticleActivity extends RingBaseActivity {

	private TextView mTitle; // 标题

	private WebView mBrowser;

	private String pageTemplate = "file:///android_asset/show_article.html"; // 详细页面载入的HTML
	private String date;
	private String title;
	private int screenHeigt;
	private String content;

	MenuBo menuConfigBo;

	private boolean switchLoading = false;

	@Override
	protected void initComponents() {
		mBrowser = (WebView) findViewById(R.id.article_browser);

		mTitle = (TextView) findViewById(R.id.top_title);

		initWebView();
	}

	@Override
	protected void initData() {
		Message message = (Message) getIntent().getSerializableExtra(
				NotificationConstants.NOTIFICATION_MESSAGE);

		ArticleBo bo = new ArticleBo(this, new GetDetailContentCallback(), null);
		String url = message.getCustom();
		if (!StringUtil.isEmpty(url)) {
			bo.setParams(Html.fromHtml(url).toString());
			bo.request();
		}
	}

	class GetDetailContentCallback implements HttpCallBack<ArticleResp> {

		@Override
		public void call(ArticleResp response) {
			if (response.isSuccess()) {
				Article article = response.getArticle();
				content = article.getContent();
				title = article.getTitle();
				date = article.getDate();

				// 设置标题
				mTitle.setText("推送消息");

				// 加载页面
				mBrowser.loadUrl(pageTemplate);
			}
		}

		@Override
		public void progress(Object... obj) {
		}

		@Override
		public void onNetWorkError() {
		}

	}

	@SuppressLint("SetJavaScriptEnabled")
	private void initWebView() {
		mBrowser.getSettings().setJavaScriptEnabled(true);
		mBrowser.getSettings().setLoadsImagesAutomatically(true);
		mBrowser.getSettings().setPluginsEnabled(true);
		// mBrowser.setBackgroundColor(Color.rgb(0xee, 0xee, 0xee));
		mBrowser.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
		mBrowser.addJavascriptInterface(new ShowNews(), "news");

		screenHeigt = AppHelper.getScreenHeight(mContext);
	}

	public class ShowNews {
		public String getTitle() {
			return title;
		}

		public String getTime() {
			return date;
		}

		public String getBody() {
			return content;
		}

		public int getScreenHeight() {
			return screenHeigt;
		}

		public boolean getIsSumSang() {
			String brand = AppHelper.getBrand();
			String model = AppHelper.getModel();
			// System.out.println("brand:" + brand);
			// System.out.println("model:" + model);
			if (brand == null || model == null) {
				return false;
			}

			if ("SAMSUNG".equals(brand.toUpperCase())) {
				model = model.toUpperCase();
				if (model.contains("I939") || model.contains("I9300") || model.contains("I9308")) {
					return true;
				}
			}
			return false;
		}
	}

	@Override
	public void onBackPressed() {
		if (Config.initSuccess()) {
			switchToSplash();
			finish();
		} else {
			startApp();
		}
	}

	// 跳转到首页
	private void startApp() {
		boolean netWorkAvailable = CommonUtils.isNetConnectionAvailable(mContext);
		// 第一次安装，且网络异常，无法进入应用
		if (!netWorkAvailable && !installFirst()) {
			netWorkError();
			return;
		}

		if (installFirst()) {
			SharedPreferencesUtil.setBoolean(mContext, Key.K_2G3G_IMAGE_SETTING, true);
		}

		if (!switchLoading) {
			switchLoading = true;
			SystemInit.init(mContext);
			MenuDataMgr.getInstance().loadDataSqlite(mContext);
			ArticleDataMgr.getInstance().loadDataSqlite(mContext);
			requestMenuData();
		}

	}

	private void requestMenuData() {
		// 本地有菜单数据，直接跳转
		List<Menu> menus = MenuDataMgr.getInstance().getMenus(mContext);
		if (menus != null && menus.size() > 0) {
			switchToSplash();
		}

		// 网络正常，异步刷新菜单
		if (CommonUtils.isNetConnectionAvailable(mContext)) {
			menuConfigBo = new MenuBo(mContext, new MenuCall());
			menuConfigBo.request();
		}
	}

	// 网络异常，弹出对话框
	private void netWorkError() {
		String message = mContext.getString(R.string.network_error);
		AlertHelper.showMessage(mContext, message, new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				exitApp(); // 退出应用

				finish();
			}
		});
	}

	class MenuCall implements HttpCallBack<MenuResp> {
		@Override
		public void call(MenuResp response) {

			// 跳转到首页
			switchToSplash();
			updateInstallFirst(); // 更新为已安装
		}

		@Override
		public void progress(Object... obj) {
		}

		@Override
		public void onNetWorkError() {
			netWorkError();
		}
	}

	/**
	 * 第一次安装  true:是， false:已安装
	 * @return
	 */
	private boolean installFirst() {
		return SharedPreferencesUtil.getBoolean(mContext, Key.K_SP_INSTALL_FIRST);
	}

	private void updateInstallFirst() {
		SharedPreferencesUtil.setBoolean(mContext, Key.K_SP_INSTALL_FIRST, Boolean.TRUE);
	}

	private void switchToSplash() {
		Intent intent = new Intent();
		intent.setClass(mContext, SplashActivity.class);
		startActivity(intent);
	}

	@Override
	protected int getMainContentViewId() {
		return R.layout.act_push_article;
	}

	@Override
	protected Class<?> getResouceClass() {
		return R.class;
	}

	@Override
	protected String getEventID() {
		return getString(R.string.event_activity_article);
	}
}
